<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="项目id" prop="projectId">
        <el-select 
          clearable=""
          v-model="queryParams.projectId" 
          filterable 
          placeholder="请选择项目"
          style="width:240px"
          >
          <el-option
            v-for="item in project_list"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="设备id" prop="deviceId">
        <el-input
          v-model="queryParams.deviceId"
          placeholder="请输入设备id"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="图片地址" prop="imagePath">
        <el-input
          v-model="queryParams.imagePath"
          placeholder="请输入图片地址"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="识别失败信息" prop="message">
        <el-input
          v-model="queryParams.message"
          placeholder="请输入识别失败信息"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="请求业务id" prop="requestId">
        <el-input
          v-model="queryParams.requestId"
          placeholder="请输入请求业务id"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="重试次数" prop="retryTimes">
        <el-input
          v-model="queryParams.retryTimes"
          placeholder="请输入重试次数"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="人工审核" prop="isAudit">
        <el-select v-model="queryParams.isAudit" placeholder="请选择" clearable>
          <el-option
            v-for="dict in dict.type.is_audit"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
        <!-- <el-input
          v-model="queryParams.isAudit"
          placeholder="请输入是否需要人工审核(0：不需要，1：需要)"
          clearable
          @keyup.enter.native="handleQuery"
        /> -->
      </el-form-item>
      <el-form-item label="审核人" prop="auditor">
        <el-input
          v-model="queryParams.auditor"
          placeholder="请输入审核人"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!-- <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['produce:platform-arithmetic-invoke-record:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['produce:platform-arithmetic-invoke-record:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['produce:platform-arithmetic-invoke-record:removed']"
        >删除</el-button> -->
      <!-- </el-col> -->
      <!-- <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['produce:platform-arithmetic-invoke-record:export']"
        >导出</el-button>
      </el-col> -->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="PlatformArithmeticInvokeRecordList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="" align="center" prop="id" />
      <el-table-column label="项目id" align="center" prop="projectId" />
      <el-table-column label="设备id" align="center" prop="deviceId" />
      <el-table-column label="识别结果数据" align="center" prop="data" />
      <el-table-column label="图片地址" align="center" prop="imagePath" />
      <el-table-column label="识别失败信息" align="center" prop="message" />
      <el-table-column label="请求业务id" align="center" prop="requestId" />
      <el-table-column label="0:识别中  1：识别完成  2：识别失败" align="center" prop="status" />
      <el-table-column label="重试次数" align="center" prop="retryTimes" />
      <el-table-column label="算法类型" align="center" prop="type" />
      <el-table-column label="是否需要人工审核(0：不需要，1：需要)" align="center" prop="isAudit" />
      <el-table-column label="审核人" align="center" prop="auditor" />
      <el-table-column label="冰柜类型" align="center" prop="containerType" />
      <el-table-column label="备注" align="center" prop="remark" />
      <!-- <el-table-column label="是否移除" align="center" prop="removed" /> -->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            v-show = "scope.row.isAudit === 1"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdateDataResult(scope.row)"
            v-hasPermi="['produce:platform-arithmetic-invoke-record:edit']"
          >人工修改识别结果</el-button>
          <!-- <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['produce:platform-arithmetic-invoke-record:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['produce:platform-arithmetic-invoke-record:removed']"
          >删除</el-button> -->
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改平台算法调用记录对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="项目id" prop="projectId">
          <el-input v-model="form.projectId" placeholder="请输入项目id" />
        </el-form-item>
        <el-form-item label="设备id" prop="deviceId">
          <el-input v-model="form.deviceId" placeholder="请输入设备id" />
        </el-form-item>
        <el-form-item label="识别结果数据" prop="data">
          <el-input v-model="form.data" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="图片地址" prop="imagePath">
          <el-input v-model="form.imagePath" placeholder="请输入图片地址" />
        </el-form-item>
        <el-form-item label="识别失败信息" prop="message">
          <el-input v-model="form.message" placeholder="请输入识别失败信息" />
        </el-form-item>
        <el-form-item label="请求业务id" prop="requestId">
          <el-input v-model="form.requestId" placeholder="请输入请求业务id" />
        </el-form-item>
        <el-form-item label="重试次数" prop="retryTimes">
          <el-input v-model="form.retryTimes" placeholder="请输入重试次数" />
        </el-form-item>
        <el-form-item label="是否需要人工审核(0：不需要，1：需要)" prop="isAudit">
          <el-input v-model="form.isAudit" placeholder="请输入是否需要人工审核(0：不需要，1：需要)" />
        </el-form-item>
        <el-form-item label="审核人" prop="auditor">
          <el-input v-model="form.auditor" placeholder="请输入审核人" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog title="修改算法结果" :visible.sync="toEditRecResultDialogOpen" :close-on-click-modal="false"
      @close="cancel" width="75%" destroy-on-close destroy-on-closescope>
      <div class="analy-container" style="height: 1000px;width: 100%;">
        <div ref="editRecResultCanvasBox" style="float: left;">
          <canvas ref="canvas"></canvas>
        </div>
        <div ref="canvasEditBox" style="border:1px solid red;width: 600px;height: 600px;margin-left:10%;margin-top: 20%;float: left;">
        <!-- <div>算法skuId：
          <el-select v-model="alogSkuId" placeholder="请选择要添加小图的算法" clearable filterable>
            <el-option v-for="item in arithmetic_list" :key="item.id"
              :label="item.id + '-' + item.name + ' (' + (item.layer === 1 ? '顶' : (item.layer === 2 ? '中间' : '底')) + ')'"
              :value="item.id" />
          </el-select>
          <el-button size="mini" type="text" @click="handleAdd()" style="margin-left: 20px;">新增小图</el-button>
          <el-button size="mini" type="text" @click="handleDownload()" style="margin-left: 20px;">下载截取图片</el-button>
        </div> -->
        <div>
          <div>选中的商品信息为：</div>
          <div style="margin-top: 5px;">skuName（商品名称）:   </div>
          <div style="color:green">{{ this.nowChooseGoodParams.customerSkuName}}</div>
          <div style="margin-top: 5px;">skuId(商品Id):  </div>
          <div style="color:green">{{ this.nowChooseGoodParams.customerSkuId}}</div>

        </div>

        <div style="margin-top: 20px">
          <div>需要替换为：</div>
          <!-- <div>
            选择商品：
            <el-select v-model="editItem" placeholder="选择要替换成的商品" clearable filterable @change="handleEditItemChange">
              <el-option v-for="item in PlatformProjectSegGoodsList" :key="item.id"
                :label="item.name"
                :value="item.id" 
                
                />
            </el-select>
          </div> -->
          <div>skuId:
            <el-input v-model="editedGoodParams.customerSkuId" placeholder="请输入skuId" />
          </div>
          <div>skuName：
            <el-input v-model="editedGoodParams.customerSkuName" placeholder="请输入商品名称" />
          </div>
          <div>
            <el-button type="primary" @click="editGoodsParams">确 定</el-button>
          </div>
        </div>
        <div style="width: 600px;height: 500px;">
          <div style="width: 50%;height: 100%;float: left;">
            截取的图片：
            <canvas id="canvasSingle" ref="canvasSingle" width="300" height="300"></canvas>
          </div>
          <!-- <div style="width: 49%;height: 100%;float: left;position: relative;">
            <div>主图：</div>
            <div><img :src="this.nowMainPicUrl" style="max-width: 100%;height: auto;"></div>
            <div style="float: left;margin-top: 10px;height: 20px;line-height: 20px;">{{ this.nowMainPicName }}</div>
          </div> -->
        </div>
      </div>

      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="confirmEdit">确认修改</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { fabric } from 'fabric';
import { listPlatformArithmeticInvokeRecord, getPlatformArithmeticInvokeRecord, removedPlatformArithmeticInvokeRecord, addPlatformArithmeticInvokeRecord, updatePlatformArithmeticInvokeRecord } from "@/api/arithmetic/platform-arithmetic-invoke-record";
import { listProject } from "@/api/project/project";
export default {
  name: "Platform-arithmetic-invoke-record",
  dicts: ['is_audit'],
  data() {
    return {
      editedGoodParams:{
        customerSkuName:null,
        customerSkuId:null
      },
      // 当前选中的商品参数
      nowChooseGoodParams:{
        customerSkuName:null,
        customerSkuId:null
      },
      // 打开修改识别结果弹窗
      toEditRecResultDialogOpen: false,
      // 新识别结果
      newResult:null,
      // 老识别结果
      oldResult:null,
      // 项目列表
      project_list:[],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 平台算法调用记录表格数据
      PlatformArithmeticInvokeRecordList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        projectId: null,
        deviceId: null,
        data: null,
        imagePath: null,
        message: null,
        requestId: null,
        status: null,
        retryTimes: null,
        type: null,
        isAudit: 1,
        auditor: null,
        containerType: null,
        removed: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        status: [
          { required: true, message: "0:识别中  1：识别完成  2：识别失败不能为空", trigger: "change" }
        ],
        retryTimes: [
          { required: true, message: "重试次数不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
    this.getProjectList();
  },
  methods: {
    /** 确定覆盖 */
    confirmEdit(){
      console.log("确认提交",this.oldResult)
      updatePlatformArithmeticInvokeRecord(this.oldResult).then(response => {
        this.$modal.msgSuccess("修改算法结果成功");
        this.toEditRecResultDialogOpen = false;
        this.getList();
      });
    },
    // 修改选中的商品名和商品id
    editGoodsParams(){
      // 找出原数组对应的商品数据
      let nowGoods = this.oldResult.jsonResult.find((item) => ((item.outputJniSeg.center_x == this.nowChooseGoodParams.outputJniSeg.center_x) && (item.outputJniSeg.center_y == this.nowChooseGoodParams.outputJniSeg.center_y)) )
      nowGoods.customerSkuId = this.editedGoodParams.customerSkuId;
      nowGoods.customerSkuName = this.editedGoodParams.customerSkuName;
      let index = this.oldResult.jsonResult.indexOf(nowGoods);
      console.log("为当前数组的第"+index);
      console.log(nowGoods)
      this.oldResult.jsonResult[index] = nowGoods;
      console.log(this.oldResult.jsonResult)
      console.log(JSON.stringify(this.oldResult.jsonResult));
      console.log(this.oldResult.data)
      this.oldResult.data = JSON.stringify(this.oldResult.jsonResult)
    },
    /** 获取项目列表 */
    getProjectList(){
      listProject().then((res) =>{
        if(res.code === 200 && res.rows){
          this.project_list = res.rows.map((item) =>{
            return {label:item.projectName,value:item.id.toString()}
          })
          console.log(this.project_list)
        }
      }).catch((err) =>{
        this.$message.error("项目列表获取失败，原因："+err.message)
      }).finally(() =>{

      })
    },
    /** 查询平台算法调用记录列表 */
    getList() {
      this.loading = true;
      listPlatformArithmeticInvokeRecord(this.queryParams).then(response => {
        this.PlatformArithmeticInvokeRecordList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.toEditRecResultDialogOpen = false;
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.oldResult = null;
      this.newResult = null;
      this.form = {
        id: null,
        projectId: null,
        deviceId: null,
        data: null,
        imagePath: null,
        message: null,
        requestId: null,
        status: null,
        retryTimes: null,
        type: null,
        isAudit: null,
        auditor: null,
        containerType: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
        removed: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加平台算法调用记录";
    },
    /** 手动更改按钮操作 */
    handleUpdateDataResult(row){
      this.reset();
      const id = row.id || this.ids
      getPlatformArithmeticInvokeRecord(id).then(response => {
        this.form = response.data;
        // this.open = true;
        // this.title = "修改平台算法调用记录";
        console.log(response.data.data)
        if((!response.data.data) || (response.data.data == '[]')){
          this.$message.warning("该图片无算法识别数据返回")
        }else{
          console.log("do something")
          this.oldResult = response.data
          this.oldResult.jsonResult = JSON.parse(response.data.data)
          console.log(this.oldResult.jsonResult)
          console.log("识别出来的商品总数为:"+this.oldResult.jsonResult.length)
          // 打开弹窗
          this.toEditRecResultDialogOpen = true;
          // 绘图
          this.toDrawSegResult();
        }
      });
    },
    /** 绘图 */
    async toDrawSegResult(){
      console.log("风幕柜图片的url为", this.oldResult.interiorImagePath);
      console.log("风幕柜商品对应关系为", this.oldResult.jsonResult);
      //1.异步操作都在nextTick中返回
      this.$nextTick(() => {
        // const h = 500
        const h = 1000
        this.$refs.editRecResultCanvasBox.style.height = h + 'px'
        //对图片进行渲染-图像文件的加载是异步的，所有对Image的后续操作都要在回调中完成
        fabric.Image.fromURL(
          this.oldResult.interiorImagePath,
          (img) => {
            let w
            img.set({ selectable: false })
            img.scaleToWidth(860)  //指定宽度
            img.scaleToHeight(1000)  //指定图片高度
            w = img.width * img.scaleX
            const canvas = new fabric.Canvas(this.$refs.canvas, {
              width: w,
              height: h,
              centeredRotation: true,
            })
            canvas.add(img)
            console.log("给canvas塞入主图")
            let results = []
            try {
              results = this.oldResult.jsonResult || []
              // 用商品名替换掉算法名
              // if (results.length > 0) {
              //   results.forEach((item) => {
              //     this.SegBaseSkuList.forEach((skuItem) => {
              //       if (item.id == skuItem.soId) {
              //         item.name = item.confidence.toFixed(2) + " " + skuItem.name + " " + item.confidence.toFixed(2)
              //       }
              //     })
              //   })
              // }
            } catch (error) { }
            // 1 本品 绿色框 2 竞品 红色框 3 未知 蓝色框
            const strokeColors = ['#669933', '#ff6666', '#99CCFF']
            const shadowColors = ['green', 'red', 'blue']
            const colroI = parseInt(Math.random() * 3)
            // const stroke = strokeColors[colroI]
            // const shadowColor = shadowColors[colroI]
            // 绘制不规则图形
            for (var i = 0; i < this.oldResult.jsonResult.length; i++) {
              let loc = this.oldResult.jsonResult[i]
              let pointList = this.oldResult.jsonResult[i].outputJniSeg.coordinate
              for (var k = 0; k < pointList.length; k++) {
                var path = 'M'
                for (var q = 0; q < pointList[k].length; q++) {
                  if (q === 0) {
                    path = path + " " + pointList[k][q].x * img.scaleX + ' ' + pointList[k][q].y * img.scaleY
                  } else {
                    path = path + ' L ' + pointList[k][q].x * img.scaleX + ' ' + pointList[k][q].y * img.scaleY
                  }
                }
                path = path + 'z'
                var fabricPath = new fabric.Path(path);
                // 对象配置
                fabricPath.set({
                  stroke: "green",
                  fill: 'transparent',
                  lockMovementX: true,
                  lockMovementY: true,
                  hasControls: false,
                  hasBorders: false
                });
                // 点击显示的文字
                var text = new fabric.Text(loc.customerSkuName, {
                  ...loc.outputJniSeg,
                  fontSize: 14,
                  textBackgroundColor: 'black',
                  fill: 'white'
                })
                console.log("字体")
                console.log(text)
                // 字体位置
                text.set('left',text.center_x * img.scaleX)
                // text.set('top',text.center_y * img.scaleY)
                // text.set('left', text.box_x * img.scaleX - text.box_width * img.scaleX / 2)
                text.set('top', text.box_y * img.scaleY - 20)
                var fabricPathSelected = new fabric.Path(path);
                // 选中对象配置
                fabricPathSelected.set({
                  stroke:'balck',
                  strokeWidth: 4,
                  fill: 'transparent',
                  lockMovementX: true,
                  lockMovementY: true,
                  hasControls: false,
                  hasBorders: false
                });
                const tg = new fabric.Group([fabricPathSelected, text], {
                  lockMovementX: true,
                  lockMovementY: true,
                  hasControls: false,
                  hasBorders: false,
                })
                fabricPath.on('selected', () => {
                  canvas.add(tg)
                  console.log(tg)
                  console.log(loc)
                  console.log(loc.customerSkuName)
                  console.log(loc.customerSkuId)
                  // console.log(loc.)
                  this.nowChooseGoodParams = loc
                  // rect.set('stroke', shadowColor)
                  // rect.set('strokeWidth', 4)
                  // canvas.add(tg)
                  let drawing = document.getElementById('canvasSingle')
                  // if(drawing.getContext){
                  // const canvas2 = new fabric.Canvas(this.$refs.canvasSingle, {
                  //   width: rect.width * 3,
                  //   height: rect.height * 3,
                  //   centeredRotation: true,
                  // })

                  var image = new Image()
                  image.src = this.oldResult.interiorImagePath
                  // canvas2.add(img)
                  let context = drawing.getContext('2d')
                  context.drawImage(
                    image, //要绘制的图像
                    tg.left / (562.5 / img.width), //源图像x坐标
                    tg.top / (1000 / img.height), //源图像y坐标
                    tg.width / (562.5 / img.width), //源图像宽度
                    tg.height / (1000 / img.height), //源图像高度
                    0, //目标区域x坐标
                    0, //目标区域y坐标
                    tg.width * 3, //目标区域宽度
                    tg.height * 3 //目标区域高度
                  )
                  let imageUrl = this.$refs.canvasSingle.toDataURL('image/jpeg')
                  this.nowAddFile = this.base64ToFile(imageUrl, 'cut' + tg.left + tg.top + '.jpg')
                  this.nowAddUrl = imageUrl
                  console.log(this.nowAddUrl)
                  // this.cutPicNum++
                  //展示主图
                  // if (loc.url) {
                  //   this.nowMainPicUrl = loc.url
                  // } else {
                  //   this.nowMainPicUrl = ''
                  // }
                  // if (loc.skuNameShow) {
                  //   this.nowMainPicName = loc.skuNameShow
                  // } else {
                  //   this.nowMainPicName = ''
                  // }
                })
                fabricPath.on('deselected', () => {
                  canvas.remove(tg)
                })
                canvas.add(fabricPath)
              }
            }





            // const canvas = document.querySelector('#canvas')
            // const c2 = canvas.getContext('2d')

            // // 设置属性控制图形的外观
            // c2.fillStyle = 'rgba(255, 255, 255, 0)'
            // // 外部使用外边框
            // c2.strokeStyle = '#ff0000'
            // // 线宽
            // c2.lineWidth = 2
            // c2.beginPath()
            // for (let i = 0; i <this.point_list.length; i++) {
            //     const data = this.point_list[i]
            //     if (i === 0) {
            //         c2.moveTo(data.x, data.y)
            //     }else {
            //         c2.lineTo(data.x , data.y)
            //     }
            // }
            // c2.closePath()
            // c2.fill()
            // c2.stroke()
            // canvas.add(c2)
            // for (let i = 0; i < results.length; i++) {
            //   const res = results[i]
            //   const loc=results[i]
            //   loc.top = loc.y * img.scaleY //y
            //   loc.height = loc.height * img.scaleY
            //   loc.left = loc.x * img.scaleX   //x
            //   loc.width = loc.width * img.scaleX
            //   if (!loc) continue
            //   const colroI = parseInt(Math.random() * 3)
            //   const stroke = strokeColors[colroI]
            //   const shadowColor = shadowColors[colroI]
            //   const shadow = new fabric.Shadow({ color: shadowColor, blur: 0 })
            //   const rect = new fabric.Rect({
            //     ...loc,
            //     fill: 'transparent',
            //     strokeWidth: 2,
            //     stroke,
            //     lockMovementX: true,
            //     lockMovementY: true,
            //     hasControls: false,
            //     hasBorders: false,
            //   })
            //   const text = new fabric.Text(loc.skuName, {
            //     ...loc,
            //     fontSize: 14,
            //     stroke: shadowColor,
            //   })
            //   text.set('left', text.left - text.width / 2 + loc.width / 2)
            //   text.set('top', text.top - text.height)
            //   const Trect = new fabric.Rect({
            //     top: text.top,
            //     left: text.left,
            //     width: text.width,
            //     height: text.height,
            //     fill: '#ffffff',
            //   })
            //   const tg = new fabric.Group([Trect, text], {
            //     lockMovementX: true,
            //     lockMovementY: true,
            //     hasControls: false,
            //     hasBorders: false,
            //   })
            //   rect.on('selected', () => {
            //       rect.set('stroke', shadowColor)
            //       rect.set('strokeWidth', 4)
            //       canvas.add(tg)
            //         let drawing = document.getElementById('canvasSingle')
            //         // if(drawing.getContext){
            //           const canvas2 = new fabric.Canvas(this.$refs.canvasSingle, {
            //             width: rect.width * 3,
            //             height: rect.height * 3,
            //             centeredRotation: true,
            //           })

            //           var image = new Image()
            //           image.src = this.showUrl
            //           // canvas2.add(img)
            //           let context = drawing.getContext('2d')

            //           context.drawImage(
            //             image, //要绘制的图像
            //             rect.left/(562.5/img.width), //源图像x坐标
            //             rect.top/(1000/img.height), //源图像y坐标
            //             rect.width/(562.5/img.width), //源图像宽度
            //             rect.height/(1000/img.height), //源图像高度
            //             0, //目标区域x坐标
            //             0, //目标区域y坐标
            //             rect.width * 3, //目标区域宽度
            //             rect.height * 3 //目标区域高度
            //           )

            //           let imageUrl = this.$refs.canvasSingle.toDataURL('image/jpeg')
            //           this.nowAddFile = this.base64ToFile(imageUrl,'cut'+rect.left+rect.top+'.jpg')
            //           this.nowAddUrl = imageUrl
            //           this.cutPicNum++

            //           //展示主图
            //           if(loc.url){
            //             this.nowMainPicUrl = loc.url
            //           }else{
            //             this.nowMainPicUrl = ''
            //           }
            //           if(loc.skuNameShow){
            //             this.nowMainPicName = loc.skuNameShow
            //           }else{
            //             this.nowMainPicName = ''
            //           }
            //   })
            //   rect.on('deselected', () => {
            //     // rect.shadow.blur = 0
            //     // rect.shadow.color = stroke
            //     rect.set('stroke', stroke)
            //     rect.set('strokeWidth', 2)
            //     canvas.remove(tg)
            //   })
            //   canvas.add(rect)
            // }
            canvas.renderAll()
          },
          { crossOrigin: 'anonymous' }
        )
      })
    },
    /** base64转文件 */
    base64ToFile(base64, fileName) {
      let arr = base64.split(",");
      // let mime = arr[0].match(':')[1];
      let mime = 'image/png'
      let bstr = atob(arr[1]);
      let n = bstr.length;
      let u8arr = new Uint8Array(n);

      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new File([u8arr], fileName, { type: mime });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getPlatformArithmeticInvokeRecord(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改平台算法调用记录";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updatePlatformArithmeticInvokeRecord(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addPlatformArithmeticInvokeRecord(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除平台算法调用记录编号为"' + ids + '"的数据项？').then(function() {
          // 修改为逻辑删除
        return removedPlatformArithmeticInvokeRecord(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('produce/platform-arithmetic-invoke-record/export', {
        ...this.queryParams
      }, `platform-arithmetic-invoke-record_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
